package com.bbc.service.user.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bbc.base.page.MysqlPaginatedArrayList;
import com.bbc.base.page.PaginatedList;
import com.bbc.entity.user.User;
import com.bbc.entity.user.UserQuery;
import com.bbc.mapper.user.UserMapper;
import com.bbc.service.user.UserService;
import com.bbc.util.PwdUtils;

@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private transient UserMapper userMapper;

	@Override
	public Integer addUser(User user) {
		return userMapper.addUser(user);
	}

	@Override
	public List<User> findUser(UserQuery query,int page,int pageSize) {
		PaginatedList<User> list = new MysqlPaginatedArrayList<User>(page,pageSize);
		list.setTotalItem(userMapper.findUserCount(query));
		query.setStartRow(list.getStartRow());
		query.setEndRow(list.getEndRow());
		list.addAll(userMapper.findUser(query));
		return list;
	}

	@Override
	public void updateUser(User user) {
		userMapper.updateUser(user);
	}

	@Override
	public User findUserById(Integer id) {
		UserQuery q = new UserQuery();
		q.setId(id);
		if (userMapper.findUserCount(q) == 1) {
			return userMapper.findUser(q).get(0);
		}
		return null;
	}

	@Override
	public User findUserByNP(String name, String pwd) {
		UserQuery q = new UserQuery();
		q.setName(name);
		q.setPwd(pwd);
		if (userMapper.findUserCount(q) == 1) {
			return userMapper.findUser(q).get(0);
		}
		return null;
	}

	@Override
	public User login(User user) {
		if (user == null) {
			return null;
		}
		//TODO 临时存name和mail为同一值
		user.setName(user.getMail());
		if (StringUtils.isEmpty(user.getName()) || StringUtils.isEmpty(user.getPassword())) {
			return null;
		}
		String pwd = PwdUtils.build(user.getPassword());
		if (pwd == null) {
			return null;
		}
		return findUserByNP(user.getName(), pwd);
	}

	@Override
	public boolean check(String type, String value) {
		UserQuery q = new UserQuery();
		if ("nick".equals(type)) {
			q.setNick(value);
		} else if ("mail".equals(type)) {
			q.setMail(value);
		} else {
			return false;
		}
		int count = userMapper.findUserCount(q);
		if (count==1) {
			return true;
		} else {
			return false;
		}
	}

}
